package com.lichuandi.device;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Random;

/**
 * 设备端
 * @author admin
 */
public class DeviceSimulator {
    public static void main(String[] args) throws InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        String serverUrl = "http://localhost:8080/api/data";

        Random rand = new Random();
        while (true) {
            // 生成虚拟温湿度数据
            double temperature = 20 + rand.nextDouble() * 10;
            // 40-60%
            double humidity = 40 + rand.nextDouble() * 20;

            // 构造JSON数据
            String json = String.format(
                    "{\"deviceId\":\"DEV001\",\"temp\":%.1f,\"humidity\":%.1f}",
                    temperature, humidity
            );

            // 发送HTTP POST请求到云端
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(serverUrl))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(json))
                    .build();

            try {
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                System.out.println("数据发送成功: " + response.statusCode());
            } catch (Exception e) {
                System.out.println("发送失败: " + e.getMessage());
            }
            // 每5秒发送一次
            Thread.sleep(5000);
        }
    }
}
